package cn.hzu.sotacy.service.impl.video;

import cn.hzu.sotacy.model.vedio.Video;
import cn.hzu.sotacy.dao.video.VideoDao;
import cn.hzu.sotacy.response.ApiRestResponse;
import cn.hzu.sotacy.result.CodeResult;
import cn.hzu.sotacy.service.vedio.VideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2021-12-23
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoDao, Video> implements VideoService {

    private static final String savePaths = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\video";

    @Resource
    VideoDao videoDao;

    /**
     * 添加视频
     * @param request  请求
     * @param uploadFile 上传文件
     * @return cn.hzu.sotacy.response.ApiRestResponse<cn.hzu.sotacy.model.vedio.Video>
     * @author Jasper Zhan
     * @date 2021/12/23 14:56
     */
    @Override
    public ApiRestResponse<Video> addVideo(HttpServletRequest request, MultipartFile uploadFile) {

        String courseUnitId = request.getParameter("courseUnitId");
        String name = request.getParameter("name");
        String describe = request.getParameter("describe");

        if (uploadFile == null)
            return ApiRestResponse.fail(CodeResult.EMPTY_VIDEO_FILE);

        Video video = new Video();

        if (courseUnitId == null || courseUnitId.equals("") || courseUnitId.equals("undefined"))
            return ApiRestResponse.fail(CodeResult.EMPTY_COURSE_UNIT_ID);

        video.setCourseUnitId(Integer.valueOf(courseUnitId));

        if (name == null || name.equals(""))
            return ApiRestResponse.fail(CodeResult.EMPTY_VIDEO_NAME);

        video.setName(name);

        System.out.println(uploadFile.getName());

        //获取文件后缀
        String fileExt = Objects.requireNonNull(uploadFile.getOriginalFilename())
                .substring(uploadFile.getOriginalFilename().lastIndexOf(".") + 1)
                .toLowerCase();

        // 重构文件名称
        String pikId = UUID.randomUUID().toString().replaceAll("-", "");
        String newVideoName = pikId + "." + fileExt;

        //保存视频
        File fileSave = new File(savePaths, newVideoName);
        if (!fileSave.isDirectory()) {//文件目录不存在，就创建一个
            fileSave.mkdirs();
        }

        try {
            uploadFile.transferTo(fileSave);
        } catch (IOException e) {
            e.printStackTrace();
            return ApiRestResponse.fail(CodeResult.FAIL_VIDEO_SAVE);
        }

        video.setUrl(newVideoName);
        video.setDescribe(describe);

        save(video);

        return ApiRestResponse.success(CodeResult.SUCCESS_ADD_VIDEO, video);
    }

    /**
     * 查看视频
     * @param request  请求
     * @param response 回复
     * @return cn.hzu.sotacy.response.ApiRestResponse<cn.hzu.sotacy.model.vedio.Video>
     * @author Jasper Zhan
     * @date 2021/12/31 16:47
     */
    @Override
    public ApiRestResponse<Video> getVideo(HttpServletRequest request, HttpServletResponse response) {

        String sCourseUnitId = request.getParameter("courseUnitId");

        if (sCourseUnitId == null || sCourseUnitId.equals(""))
            return ApiRestResponse.fail(CodeResult.EMPTY_COURSE_UNIT_ID);

        int courseUnitId;

        try {
            courseUnitId = Integer.parseInt(sCourseUnitId);
        } catch (NumberFormatException e) {
            return ApiRestResponse.fail(CodeResult.ERROR_FORMAT_COURSE_UNIT_ID);
        }

        QueryWrapper<Video> wrapper = new QueryWrapper<>();
//        wrapper.eq("course_unit_id", courseUnitId);

//        Video video = getOne(wrapper);
        Video video = videoDao.getByCourseUnitId(courseUnitId);
        if (video == null)
            return ApiRestResponse.fail(CodeResult.EMPTY_VIDEO_OF_COURSE_UNIT);

        String url = savePaths + "\\" + video.getUrl();
        System.out.println(url);

        try {
            //	获得视频文件的输入流
            FileInputStream inputStream = new FileInputStream(url);
            // 创建字节数组，数组大小为视频文件大小
            byte[] data = new byte[inputStream.available()];
            // 将视频文件读入到字节数组中
            inputStream.read(data);
            String diskfilename = "final.mp4";
            // 设置返回数据格式
            response.setContentType("video/mp4");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"");
            System.out.println("data.length " + data.length);
            response.setContentLength(data.length);
            response.setHeader("Content-Range", "" + Integer.valueOf(data.length - 1));
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Etag", "W/\"9767057-1323779115364\"");
            // 获得 response 的字节流
            OutputStream os = response.getOutputStream();
            // 将视频文件的字节数组写入 response 中
            os.write(data);
            //先声明的流后关掉！
            os.flush();
            os.close();
            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
            return ApiRestResponse.fail(CodeResult.ERROR_GET_VIDEO);
        }

        return ApiRestResponse.success(CodeResult.SUCCESS_GET_VIDEO);
    }
}
